<?php

namespace App\Http\Controllers;


use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;


class HomeController extends Controller
{
    public function index(){


        $banner = DB::table('banner')->limit(6)->orderBy('id','desc')->get();
        $banner = objectToArray($banner);
        foreach ($banner as $k=>$v){
            $banner[$k]['image'] = config('app.url').'/upload/'.$v['image'];
        }

        $lists = DB::table('category')->orderBy('id','asc')->get()->toArray();
        $lists = objectToArray($lists);
        foreach ($lists as $k=>$v){
            if (gettype($v)=='object'){
                $v = get_object_vars($v);
                $lists[$k] = $v;
            }
            $news = DB::table('news')->limit(3)->where("category_id",$v['id'])->orderBy('is_recomend','desc')->orderBy('id','desc')->get();
            $news =objectToArray($news);
            foreach ($news as $k1=>$v1){
                $news[$k1]['image'] = config('app.url').'/upload/'.$v1['image'];
            }
            $lists[$k]['news'] = $news;
        }

        $ad = DB::table('ad')->limit(1)->orderBy('id','desc')->first();
        if($ad){
            $ad =  objectToArray($ad);
            $ad['image'] = config('app.url').'/upload/'.$ad['image'];

        }

        $data = [
            'banner'=>$banner,
            'lists'=>$lists,
            'ad'=>$ad,
        ];
        return response()->json(['code'=>0,'data'=>$data]);
    }

    public function addFree(Request $request){

        $ad_id = $request->input('ad_id',0);
        $user_id = $request->input('user_id',0);
        $data = DB::table('ad')->where('id',$ad_id)->first();
        if (empty($data)){
            return response()->json(['code'=>10002,'msg'=>'广告不存在']);
        }
        $data =  objectToArray($data);
        $now = date('Y-m-d',time());
        $res = DB::table('free')->whereDate('created_at', $now)->where('ad_id',$ad_id)->where('user_id',$user_id)->first();
        if (!empty($res)){
            return response()->json(['code'=>10004,'msg'=>'当日只能操作一次']);
        }

        $temp = [
            'ad_id'=>$ad_id,
            'user_id'=>$user_id,
            'one_num'=>$data['one_num'],
            'created_at'=>date('Y-m-d H:i:s'),
        ];
        $res = DB::table('free')->insertGetId($temp);
        $temp['id'] = $res;

        return response()->json(['code'=>0,'data'=>$temp]);

    }



}
